package cn.jasonone.bbs.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import cn.jasonone.bbs.bean.Comment;
import cn.jasonone.bbs.bean.UserInfo;
import cn.jasonone.bbs.consts.ApplicationConsts;
import cn.jasonone.bbs.model.Result;
import cn.jasonone.bbs.service.CommentService;

@Controller
@RequestMapping("/comment")
public class CommentController {
	@Resource
	private CommentService commentService;

	@GetMapping
	public String comment(String articleId, String pid, ModelMap map) {
		map.put("articleId", articleId);
		map.put("pid", pid);
		return "comment/comment";
	}

	@GetMapping({ "/{articleId}/{pid}", "/{articleId}" })
	public String comment(@PathVariable("articleId") String articleId,
			@PathVariable(name = "pid", required = false) String pid, Map<String, Object> map) {
		map.put("articleId", articleId);
		map.put("pid", pid);
		return "comment/comment";
	}

	@PostMapping("/add")
	@ResponseBody
	public Result comment(Comment comment,
			@SessionAttribute(ApplicationConsts.LOGIN_STATUS_SESSION) UserInfo userInfo) {
		try {
			comment.setCreatedBy(userInfo.getId());
			if (comment.getPid() == null) {
				comment.setPid(-1L);
			}
			commentService.insert(comment);
			return Result.success().setMsg("评论成功");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(500).setMsg("评论失败").add("error", e.getMessage());
		}
	}

	@GetMapping("/query/{articleId}")
	@ResponseBody
	public Result query(@PathVariable("articleId") Long articleId) {
		try {
			Comment t = new Comment();
			t.setPid(-1L);
			t.setArticleId(articleId);
			List<Comment> list = commentService.findAll(t);
			return Result.success().setMsg("查询成功").add("list", list);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(500).setMsg("查询失败").add("error", e.getMessage());
		}

	}

}
